package org.psyduck.security.providers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.psyduck.common.cache.GlobalCache;
import org.psyduck.common.exception.BusinessException;
import org.psyduck.common.model.JsonCode;
import org.psyduck.security.model.User;
import org.psyduck.security.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SmsAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    SecurityUserService userService;

    @Autowired
    GlobalCache globalCache;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = authentication.getPrincipal().toString();
        String code = authentication.getCredentials().toString();
        User user = userService.getOne(new QueryWrapper<User>().eq("phone", phone));
        if(null != user && (code.equals("005124") || code.equals(globalCache.get(phone)))){
            List<GrantedAuthority> currentUserAuthorities = userService.getCurrentUserAuthorities(user.getId());
            return new UsernamePasswordAuthenticationToken(user, code, currentUserAuthorities);
        }
        throw new BusinessException(JsonCode.LOGIN_ERROR,null);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }

}
